//
//  UserAccount.swift
//  新浪微博
//
//  Created by seteny on 16/7/12.
//  Copyright © 2016年 seteny. All rights reserved.
//

import UIKit

class UserAccount: NSObject {
    
    //用户授权的唯一凭证
    var access_token: String?
    // access_token的生命周期,单位是秒
    var expinsres_in: NSTimeInterval = 0 {
        
        didSet {
            // access_token过期视图 = 当前时间 + 过期时间
            expiresDate = NSDate().dateByAddingTimeInterval(expinsres_in)
        }
        
    }
    //过期时间
    var expiresDate: NSDate?
    
    //授权用户的Uid
    var uid: Int64 = 0
    // 用户名
    var name: String?
    // 用户头像
    var avatar_large: String?
    // kvc 构造函数
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    
    //防止字段不匹配,导致崩溃
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // MARK:   --归档与解档
    
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeInt64(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    //解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeInt64ForKey("uid")
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }
    
    //保存用户对象
    func saveUserAccount() -> Bool {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        
        let reuslt = NSKeyedArchiver.archiveRootObject(self, toFile: path)
        
        return reuslt
    }
    
    //通过路径读取用户对象
    class func loadUserAccount() -> UserAccount? {
        
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.archive")
        return NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount
    }
    
    
    
}
